@echo off
setlocal enableextensions
cls
echo Windows Process Spy - One-click Build
echo =====================================
echo.
set "VENV_PY=.venv\Scripts\python.exe"

REM Check venv; if missing, require uv and create with Python 3.11
if exist "%VENV_PY%" goto VENV_READY
where uv >nul 2>nul
if errorlevel 1 (
  echo ERROR: uv is not installed. Please install uv and retry.
  goto FAIL
)
echo INFO: Creating Python 3.11 virtual environment with uv...
uv venv --python 3.11 .venv
if errorlevel 1 (
  echo ERROR: Failed to create venv via uv.
  goto FAIL
)

:VENV_READY
if not exist "%VENV_PY%" (
  echo ERROR: venv Python executable not found.
  goto FAIL
)
"%VENV_PY%" -c "import sys; sys.exit(0 if sys.version_info[:2]==(3,11) else 1)"
if errorlevel 1 (
  echo ERROR: .venv is not Python 3.11. Delete .venv and retry.
  goto FAIL
)

echo [1/2] Installing dependencies...
"%VENV_PY%" -m ensurepip
if errorlevel 1 goto FAIL
"%VENV_PY%" -m pip install -r requirements.txt
if errorlevel 1 goto FAIL

echo [2/2] Building...
if not exist "main.py" (
  echo ERROR: main.py not found.
  goto FAIL
)
if not exist "res\icon.ico" (
  echo ERROR: res\icon.ico not found.
  goto FAIL
)
if exist "build" rmdir /s /q "build"
if exist "dist" rmdir /s /q "dist"
del /q "*.spec" 2>nul
"%VENV_PY%" -c "import tkinter" >nul 2>&1
if errorlevel 1 (
  echo ERROR: tkinter import failed in venv.
  goto FAIL
)
"%VENV_PY%" -m PyInstaller --onefile --windowed --icon=res\icon.ico --name=WindowSpyGUI --optimize=2 --clean --noconfirm main.py
if errorlevel 1 goto FAIL
"%VENV_PY%" -m PyInstaller --onefile --console --name=WindowSpyCLI --optimize=2 --clean --noconfirm cli.py
if errorlevel 1 goto FAIL

echo.
echo INFO: Preparing release package...
if not exist "release" mkdir "release"
copy /y "dist\WindowSpyGUI.exe" "release\" >nul
copy /y "dist\WindowSpyCLI.exe" "release\" >nul
@REM if exist "README.md" copy /y "README.md" "release\" >nul
@REM if exist "requirements.txt" copy /y "requirements.txt" "release\" >nul
if exist "res" (
  if not exist "release\res" mkdir "release\res"
  copy /y "res\*" "release\res\" >nul
)
echo SUCCESS: Build complete!
echo Files generated:
echo - dist\WindowSpyGUI.exe
echo - dist\WindowSpyCLI.exe
echo - release\
echo.
echo INFO: Cleaning runtime flags to avoid instant exit...
set "EXIT_FLAG=%TEMP%\windowspygui_exit_signal.txt"
if exist "%EXIT_FLAG%" del /f /q "%EXIT_FLAG%" >nul 2>&1
if exist "dist\windowspygui.lock" del /f /q "dist\windowspygui.lock" >nul 2>&1
if exist "release\windowspygui.lock" del /f /q "release\windowspygui.lock" >nul 2>&1
goto END

:FAIL
echo.
echo Build failed.
exit /b 1

:END
echo.
pause
exit /b 0
